package com.esaheki.flashcards.uiSupport;

import java.sql.SQLException;
import java.util.ArrayList;

import com.esaheki.flashcards.classes.*;
import com.esaheki.flashcards.dao.*;

/**
 * Statistic é a classe atualiza os dados estatísticos no banco de dados.
 * 
 * @author      Elton Saheki Horikoshi <esaheki@gmail.com>
 */
public class Statistic {
	
	public void updateScore() {
    	try {
    		UserDAO uDao = new UserDAO();
        	CategoryDAO cDao = new CategoryDAO();
        	CardDAO cardDao = new CardDAO();
			ArrayList<User> userList = uDao.getUserList();
			for (User user : userList) {
				ArrayList<Category> catList = cDao.getCategoryList(user);
				int sumCatTests = 0;
				int sumCatRights = 0;
				for (Category cat : catList) {
					ArrayList<Card> cardList = cardDao.getCardListByCategory(cat);
					int sumTests = 0;
					int sumRights = 0;
					for (Card card : cardList) {
						sumTests += card.getCountTests();
						sumRights += card.getCountRight();
					}
					sumCatTests += sumTests;
					sumCatRights += sumRights;
					if (sumTests <= 0) {
						cat.setAverageScore(0);
					}
					else {
						cat.setAverageScore((double)sumRights / (double)sumTests);
					}
					cDao.updateCategory(cat);
				}
				if (sumCatTests <= 0) {
					user.setAverageScore(0);
				}
				else {
					user.setAverageScore((double)sumCatRights / (double)sumCatTests);
				}
				uDao.updateUser(user);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

}
